Modeling the Joint Distribution of Wind Speed and Direction using Gaussain Mixture Models

OEN Method: Harris, Cook The parent wind speed distribution: Why Weibull? http://www.sciencedirect.com/science/article/pii/S0167610514001056

Gaussian Mixture Models, http://scikit-learn.org/stable/modules/mixture.html

1. Set up

1.1 Environment

In [1]:
%matplotlib inline
%load_ext autoreload
%autoreload 2

from import_file import *
from helpers.parallel_helper import *
load_libs()

plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
plt.rcParams['axes.xmargin'] = 0.
plt.rcParams['axes.ymargin'] = 0.

1.2 Read Data

In [2]:
file_path= './data/NCDC/uk/marham/dat.txt' 
# file_path= './data/NCDC/uk/tiree/dat.txt'  # try 4
# file_path= './data/NCDC/uk/boscombe_down/dat.txt' # 4?, numpy bug
# file_path= './data/NCDC/uk/middle_wallop/dat.txt' # good
# file_path= './data/NCDC/uk/southhamption/dat.txt' # high 0
# file_path= './data/NCDC/uk/bournemouth/dat.txt' # 4?
# file_path= "./data/NCDC/uk/bealach_na_ba/dat.txt" # 
# file_path= "./data/NCDC/uk/skye_lusa/dat.txt" # 
# file_path= "./data/NCDC/uk/south_uist_range/dat.txt" 
# file_path= "./data/NCDC/uk/holbeach/dat.txt"
# file_path= "./data/NCDC/uk/weybourne/dat.txt"
# file_path= "./data/NCDC/uk/cambridge/dat.txt"
# file_path= "./data/NCDC/uk/wattisham/dat.txt"
# file_path= "./data/NCDC/us/baltimore/dat.txt" # time too short
# file_path= "./data/NCDC/uk/benbecula/dat.txt" # truncate (untruncate in m/s), 4?

# file_path= "./data/NCDC/southeast_asia/singapore_changi/dat.txt" # 4 or 5?
# file_path= "./data/NCDC/southeast_asia/sultan_ismail/dat.txt" # 
# file_path= "./data/NCDC/southeast_asia/paya_lebar/dat.txt" # 2010-2014 has problem
# file_path= "./data/NCDC/east_asia/cheongju_intl/dat.txt" # 2005-2009  may have problem, fit is good
# file_path= "./data/NCDC/east_asia/daegu_ab/dat.txt" # recent 5 year may have problem, but fit is generally good

# file_path= "./data/NCDC/europe/landsberg_lech/dat.txt" # very good, can try 4
# file_path= "./data/NCDC/europe/neuburg/dat.txt"
# file_path= "./data/NCDC/europe/valladolid/dat.txt"
# file_path= "./data/NCDC/europe/laupheim/dat.txt" # double peak, 4; very good, trend
# file_path= "./data/NCDC/europe/avord/dat.txt" # try 4, initial speed (should be good with m/s)
# file_path= './data/NCDC/europe/ciampino/dat.txt' # try 4, bandwidth?
# file_path= "./data/NCDC/europe/holzdorf/dat.txt" # 2008 year
# file_path= "./data/NCDC/europe/huspel_aws/dat.txt"  # integer, 4?
# file_path= "./data/NCDC/europe/barayas/dat.txt" , numpy bug
# file_path= "./data/NCDC/europe/vatry/dat.txt"  # double peak, initial speed (should be good with m/s), mixed report type
# file_path= './data/NCDC/europe/tenerife_sur/dat.txt'  # some directions are blocked

# file_path= "./data/NCDC/oceania/narrandera/dat.txt" # high 0
# file_path= "./data/NCDC/oceania/brisbane_archerfield/dat.txt" # high 0
# file_path= "./data/NCDC/oceania/auckland_intl/dat.txt"  # Weird KDE shape, 4?
# file_path= "./data/NCDC/oceania/canberra/dat.txt" # high 0

# file_path= "./data/NCDC/cn/shanghai/hongqiao_intl/dat.txt" 
# file_path= "./data/NCDC/cn/shanghai/pudong/dat.txt"
# file_path= "./data/NCDC/cn/tianjin/binhai/dat.txt" # recent 5 year has small problem, good overall, few 0
# file_path= "./data/NCDC/cn/tianjin/tianjing/dat.txt" # 16 sectors
# file_path= "./data/NCDC/cn/hefei_luogang/dat.txt" # recent 5 year has small problem, good overall, few 0
# file_path= "./data/NCDC/cn/南京lukou/dat.txt" 
# file_path= "./data/NCDC/cn/shijiazhuang_zhengding/dat.txt" 
# file_path= "./data/NCDC/cn/henan_gushi/dat.txt" # 16 sectors, fit not very good
# file_path= "./data/NCDC/cn/郑州xinzheng/dat.txt" # fit is not good
# file_path= "./data/NCDC/cn/nanning_wuxu/dat.txt" # recent 5 year has problem
# file_path= './data/NCDC/cn/macau/dat.txt'  
# file_path= "./data/NCDC/cn/hk_intl/dat.txt" # few initial data

# file_path= "./data/cn_database/广州.txt" 
# file_path= "./data/cn_database/北京.txt" 

# file_path = 'TOP/hr_avg.csv' # High 0
# file_path = './data/asos/denver/hr_avg.csv'

# file_path = './data/asos/bismarck_ND/hr_avg.csv' # try 4?
# file_path = './data/asos/bismarck_ND/minute_avg.csv' 
# file_path = './data/asos/aberdeen_SD/hr_avg.csv' # only to 2012, good fit, try 2
# file_path = './data/asos/minneapolis/hr_avg.csv'

# file_path = './data/asos/lincoln_NE/hr_avg.csv' 
# file_path = './data/asos/des_moines_IA/hr_avg.csv'
# file_path = './data/asos/springfield_IL/hr_avg.csv' # good fit
In [3]:
if "cn_database" in file_path: 
    df = read_cn_database(file_path)
elif 'NCDC' in file_path:
    df = pd.read_csv(file_path, header=0, skipinitialspace=True, dtype={'HrMn':'object'})
    df.rename(columns={'Date':'date','Dir':'dir','Spd':'speed','Type':'type','I.1':'wind_type'}, inplace=True)
    df = df[['date','HrMn','type','dir','speed','wind_type' ]]
    df.dropna(subset=['dir','speed'], inplace=True)
    integer_data = True
else:
    df = pd.read_csv(file_path, header=0, skipinitialspace=True, dtype={'HrMn':'object'})
    df['type']='default'
    df['wind_type']='default'
    df = df.dropna()
    integer_data = False
    knot_unit = True
In [4]:
df['time']=pd.to_datetime(df["date"].astype(str).map(str) + df["HrMn"], format='%Y%m%d%H%M')
df.set_index(['time'], inplace=True)
df['HrMn']=df['HrMn'].astype(int)
df = df.query("(dir <= 999) & (speed < 100) & \
              (date >= 19700000) & (date < 20170000) ")
In [5]:
plot_speed_and_angle_distribution(df.speed, df.dir)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
In [6]:
# Dir [10,360]=> [0,350]
df['dir'] = df['dir'].apply(lambda x: x%360 if x < 999 else x) 
df['month'] = df['date']%10000//100
# Convert Windrose coordianates to Polar Cooridinates 
df['dir_windrose'] = df['dir']
df['dir'] = df['dir'].apply(lambda x: (90 - x)%360 if x < 999 else x)
df.describe()
Out[6]:
date HrMn dir speed month dir_windrose
count 5.306410e+05 530641.000000 530641.000000 530641.000000 530641.000000 530641.000000
mean 1.997966e+07 1163.139273 204.537768 4.677674 6.474607 198.268426
std 1.231520e+05 689.317508 139.732192 2.748018 3.444669 140.666630
min 1.973010e+07 0.000000 0.000000 0.000000 1.000000 0.000000
25% 1.989041e+07 600.000000 120.000000 2.600000 3.000000 120.000000
50% 2.000091e+07 1150.000000 210.000000 4.100000 6.000000 200.000000
75% 2.009021e+07 1750.000000 260.000000 6.200000 9.000000 260.000000
max 2.016080e+07 2355.000000 999.000000 28.300000 12.000000 999.000000
In [7]:
df.plot(y='speed',legend=True,figsize=(20,5))
Out[7]:
<matplotlib.axes._subplots.AxesSubplot at 0xd41b518>

1.2.1 Unit Detection

In [8]:
if 'knot_unit' not in globals():
    df['decimal'] = df.speed % 1
    df.decimal.hist(alpha=0.5, label='m/s', figsize=(4, 3))
    knot_unit = True if len(df.query('decimal >= 0.2')) / len(df) > 0.3 else False

    if knot_unit:
        df['speed'] = df['speed'] * 1.943845
        df['decimal'] = df.speed % 1
        df.decimal.hist(alpha=0.5, label='knot')
        # need more elaboration, some is not near an integer
        df['speed'] = df['speed'].apply(lambda x: int(round(x)))
    plt_configure(xlabel='Decimal', ylabel='Frequency', legend={'loc': 'best'}, title='Decimal Distribution')
    df.drop(['decimal'], 1,inplace=True)
print(knot_unit)
True

1.2.2 Sampling Type Selection

In [9]:
sample_type = df.query('date > 20000000')['type']
sample_type.value_counts().plot(
    kind = 'bar', title = 'Report Types Comprisement', figsize=(4,3))

report_type_most_used = sample_type.value_counts().argmax()
df = df.query("type==@report_type_most_used")

1.2.3 Sampling Time Selection

In [10]:
MID_YEAR = (min(df.date)//10000+max(df.date)//10000)//2

df['HrMn'].value_counts().sort_index().plot(kind='bar', alpha=0.5,label='Overall')
df.query('date > @MID_YEAR * 10000')['HrMn'].value_counts().sort_index().plot(
    kind='bar', alpha=0.5, label='> %s' %  MID_YEAR )

plt_configure(xlabel='Sampling Time', ylabel='Frequency', legend={'loc':'best'}, figsize=(8, 4), 
              title = 'Sampling Time Distribution, Overall and > %s ' %  MID_YEAR)
In [11]:
df['sample_time'] = df.HrMn % 100 
sample_time = df.query('date > 20000000')['sample_time']
sample_times = sample_time.value_counts()[sample_time.value_counts() > 2000]
sample_times = sample_times.index.tolist()
df = df.query("sample_time in @sample_times")
df.drop(['sample_time'], 1,inplace=True)
print(sample_times)

df['HrMn'].value_counts().sort_index().plot(kind='bar', alpha=0.5, figsize=(10, 4))
[0]
Out[11]:
<matplotlib.axes._subplots.AxesSubplot at 0xc611860>

1.3 Data Wrangling

1.3.1 Artefacts

1.3.1.1 wrong direction record

In [12]:
if integer_data:
    display(df.query("(dir % 10 >= 0.1) & (dir != 999)"))
    df = df.query('(dir % 10 <= 0.1) | (dir == 999)')
date HrMn type dir speed wind_type month dir_windrose
time

1.3.1.2 sudden increase in speed

In [13]:
# sudden increse
df['incre'] = df.speed.diff(1)
df['incre'].fillna(0, inplace=True)
df['incre_reverse'] = df.speed.diff(-1)
df['incre_reverse'].fillna(0, inplace=True)

display(df.sort_values(by='speed',ascending=False).head(10))
df['incre'].plot(kind='hist', bins=arange(-15, 15), legend=True, figsize=(8, 3))
date HrMn type dir speed wind_type month dir_windrose incre incre_reverse
time
1974-12-12 10:00:00 19741212 1000 FM-12 290 55 N 12 160 44.0 46.0
2002-01-28 17:00:00 20020128 1700 FM-12 210 54 N 1 240 27.0 27.0
1976-01-02 23:00:00 19760102 2300 FM-12 180 52 N 1 270 8.0 6.0
2001-12-28 14:00:00 20011228 1400 FM-12 170 51 N 12 280 25.0 30.0
1985-11-13 09:00:00 19851113 900 FM-12 230 50 N 11 220 40.0 45.0
2007-01-18 13:00:00 20070118 1300 FM-12 180 47 N 1 270 17.0 4.0
1976-01-03 00:00:00 19760103 0 FM-12 180 46 N 1 270 -6.0 7.0
1976-05-04 05:00:00 19760504 500 FM-12 220 44 N 5 230 30.0 31.0
1976-01-02 22:00:00 19760102 2200 FM-12 210 44 N 1 240 13.0 -8.0
2002-10-27 10:00:00 20021027 1000 FM-12 200 44 N 10 250 10.0 32.0
Out[13]:
<matplotlib.axes._subplots.AxesSubplot at 0xd3f9390>
In [14]:
incre_threshold = 20 if knot_unit else 10
print('sudden increase number', len(df.query('(incre > @incre_threshold )&(incre_reverse > @incre_threshold )')))
df = df.query('(incre < @incre_threshold )|(incre_reverse < @incre_threshold )')

# Check the max speed
display(df.sort_values(by='speed',ascending=False).head(10))
df.drop(['incre', 'incre_reverse'], 1, inplace=True)
sudden increase number 11
date HrMn type dir speed wind_type month dir_windrose incre incre_reverse
time
1976-01-02 23:00:00 19760102 2300 FM-12 180 52 N 1 270 8.0 6.0
2007-01-18 13:00:00 20070118 1300 FM-12 180 47 N 1 270 17.0 4.0
1976-01-03 00:00:00 19760103 0 FM-12 180 46 N 1 270 -6.0 7.0
1976-01-02 22:00:00 19760102 2200 FM-12 210 44 N 1 240 13.0 -8.0
2002-10-27 10:00:00 20021027 1000 FM-12 200 44 N 10 250 10.0 32.0
1990-02-26 07:00:00 19900226 700 FM-12 220 43 N 2 230 20.0 18.0
2007-01-18 15:00:00 20070118 1500 FM-12 180 43 N 1 270 -4.0 3.0
2004-03-20 16:00:00 20040320 1600 FM-12 200 43 N 3 250 3.0 8.0
1977-12-24 09:00:00 19771224 900 FM-12 210 42 N 12 240 18.0 20.0
2003-04-27 12:00:00 20030427 1200 FM-12 200 41 N 4 250 22.0 17.0

1.3.2 0 Speed

In [15]:
with_too_many_zero, null_wind_frequency = is_with_too_many_zero(df.query("(date >= 20050000)"))
delete_zero = with_too_many_zero
if delete_zero:
    df = df.query('(speed > 0)')
print(delete_zero, null_wind_frequency)
False 0.00633458105384

1.3.3 Direction re-aligment and 999

For some dataset, the 16 sectors are not record properly,

e.g. the sectors are [0,20,30,50], need to redistribute the angle into 22.5

In [16]:
display(df['dir'].value_counts().sort_index())
effective_column = df.query('dir < 999')['dir'].value_counts()[df['dir'].value_counts() > 30].sort_index()
if integer_data:
    SECTOR_LENGTH = 360/len(effective_column) 
else: 
    SECTOR_LENGTH = 10
print(len(effective_column), SECTOR_LENGTH)
0       5849
10      4575
20      5878
30      5653
40      6483
50      6282
60      7761
70      6806
80      8109
90      7603
100     7273
110     5527
120     6387
130     5869
140     7875
150     7141
160     8244
170     7583
180     9856
190     8694
200    11517
210    11372
220    16077
230    14449
240    17047
250    14047
260    13836
270    10284
280    10460
290     8782
300     9611
310     7692
320     8203
330     6630
340     6245
350     4914
999     4703
Name: dir, dtype: int64
36 10.0
In [17]:
df=realign_direction(df, effective_column)
df=fill_direction_999(df, SECTOR_LENGTH)

1.4 Time Shift Comparison

In [18]:
DIR_REDISTRIBUTE = 'even'
if DIR_REDISTRIBUTE == 'even':
    DIR_BIN = arange(-5, 360, 10) 
elif DIR_REDISTRIBUTE == 'round_up':
    DIR_BIN = arange(0, 360+10, 10) 

# Comparison between mid_year, looking for: 
# 1. Odd Even Bias
# 2. Time Shift of Wind Speed Distribution
bins = arange(0, df.speed.max() + 1)
df.query('date < @MID_YEAR * 10000')['speed'].plot(
    kind='hist', alpha=0.5,bins=bins, label='< %s' % MID_YEAR)

df.query('date > @MID_YEAR * 10000')['speed'].plot(
    kind='hist', alpha=0.5,bins=bins, label='> %s' % MID_YEAR)

plt.suptitle('Speed Comparison between year < %s, > %s ' % (MID_YEAR, MID_YEAR), fontsize = 14)
plt_configure(xlabel='Speed', ylabel='Frequency', legend=True, figsize=(8, 3))
In [19]:
df.query('date < @MID_YEAR * 10000')['dir'].plot(
    kind='hist', alpha=0.5,bins=DIR_BIN, label='< %s' % MID_YEAR)

df.query('date > @MID_YEAR * 10000')['dir'].plot(
    kind='hist', alpha=0.5,bins=DIR_BIN, label='> %s' % MID_YEAR)

plt.suptitle('Dir Comparison between year < %s, and > %s ' % (MID_YEAR, MID_YEAR), fontsize = 14)
plt_configure(xlabel='Dir', ylabel='Frequency', legend={'loc':'best'}, figsize=(8, 3), tight='x')
In [20]:
# Inspect the time shift of speed and degree distribution, and odd-even bias
check_time_shift(df)
1973 - 1974
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
1975 - 1979
1980 - 1984
1985 - 1989
1990 - 1994
1995 - 1999
2000 - 2004
2005 - 2009
2010 - 2014
2015 - 2016
In [21]:
df.resample('A').mean().plot(y='speed')
plt.gca().set_ylim(bottom=0)
df.resample('M').mean().plot(y='speed', figsize=(20,4))
plt.gca().set_ylim(bottom=0)
Out[21]:
(0, 16.0)
In [22]:
for column in ['speed', 'dir']:
    if column == 'speed':
        bins = arange(0, df[column].max()+1, 1)
    else:
        bins = arange(0, df[column].max()+10, 10)
    den, _ = np.histogram(df[column], bins=bins, density=True)
    y_top=max(den)*1.2
    for year in arange(1980, 2016):
        end_year = year
        sub_df = df[str(year):str(end_year)]
        if len(sub_df) > 5000:
            plt.figure()
            df[column].hist(bins=bins, alpha=0.3, normed=True)
            sub_df[column].hist(bins=bins, alpha=0.5, figsize=(3,1.5), normed=True)
            plt.gca().set_ylim(top=y_top)
            plt_configure(title=str(year))
    align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:524: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)
In [23]:
for column in ['speed', 'dir']:
    if column == 'speed':
        bins = arange(0, df[column].max()+1, 1)
    else:
        bins = arange(0, df[column].max()+10, 10)
    density_all, _ = np.histogram(df[column], bins=bins, density=True)
    df[column].hist(bins=bins, figsize=(5,3))

    R_squares = []
    years = []
    for year in arange(1980, 2016):
        start_year, end_year = year-1, year+1
        sub_df = df[str(start_year):str(end_year)]
        if len(sub_df) > 5000:
            density, _ = np.histogram(sub_df[column], bins=bins, density=True)
            y_mean = np.mean(density_all)
            SS_tot = np.sum(np.power(density_all - y_mean, 2))
            SS_res = np.sum(np.power(density_all - density, 2))

            R_square = 1 - SS_res / SS_tot
            R_squares.append(R_square)
            years.append(year)

    plt.figure()
    plot(years, R_squares)
    ylim = max(min(plt.gca().get_ylim()[0],0.85),0)
    plt.gca().set_ylim(bottom=ylim, top=1)
    plt_configure(figsize=(5,3))
    align_figures()

1.5 Re-distribute Direction and Speed (Optional)

e.g. Dir 50 -> -45 ~ 55, to make KDE result better

In [24]:
if integer_data:
    df = randomize_angle(df, DIR_REDISTRIBUTE, SECTOR_LENGTH)
In [25]:
if integer_data:
    if delete_zero:
        redistribute_method = 'down'
    else:
        redistribute_method = 'up'

    df, speed_redistribution_info = randomize_speed(df, redistribute_method)
Redistribute upward, e.g. 0 -> [0,1]

1.6 Generate (x,y) from (speed,dir)

In [26]:
# Cook orientation
# df['dir']= (df['dir'] + 180)%360
In [27]:
# There might be a small dot in the centre, which is due to too many zero (more than 1 speed) in center
# Scatter plot in matplot has performance issue, the speed is very slow
df['x'] = df['speed'] * cos(df['dir'] * pi / 180.0)
df['y'] = df['speed'] * sin(df['dir'] * pi / 180.0)

2. Re-select Data and Overview

2.1 Data Overview

In [28]:
## Summery of the data selection
print('Knot unit?', knot_unit)
print('Report type used:', report_type_most_used)
print('Sampling time used:', sample_times)
if 'speed_redistribution_info' in globals():
    print('Speed redistribution info:', speed_redistribution_info )

df_all_years = df # for later across-year comparison
df = df_all_years.query('(date >= 20100000) & (date < 20150000)')
# df = df.query('(HrMn == 0) and (speed >= 0.5) and (date%10000 > 900) and (date%10000 < 1000)' )
df.describe()
Knot unit? True
Report type used: FM-12
Sampling time used: [0]
Speed redistribution info: Redistribute upward, e.g. 0 -> [0,1]
Out[28]:
date HrMn dir speed month dir_windrose x y
count 4.362700e+04 43627.000000 43627.000000 43627.000000 43627.000000 43627.000000 43627.000000 43627.000000
mean 2.012063e+07 1149.480826 191.371470 9.428188 6.518395 185.404153 -1.733720 -2.092198
std 1.413450e+04 692.216184 95.134155 5.022927 3.449679 111.541762 6.974945 7.621644
min 2.010010e+07 0.000000 -4.978408 0.004328 1.000000 0.000000 -34.559390 -34.020460
25% 2.011040e+07 500.000000 111.126055 5.682482 4.000000 120.000000 -6.481890 -7.177466
50% 2.012063e+07 1100.000000 212.878414 8.680462 7.000000 190.000000 -1.169070 -2.342495
75% 2.013093e+07 1700.000000 264.126471 12.390631 10.000000 250.000000 3.232770 3.450072
max 2.014123e+07 2300.000000 354.993793 36.382502 12.000000 999.000000 21.279390 26.968835
In [29]:
df.plot(y='speed',legend=True,figsize=(20,5))
Out[29]:
<matplotlib.axes._subplots.AxesSubplot at 0x1fd43a20>
In [30]:
# df['date'].apply(lambda x: str(x)[:-2]).value_counts().sort_index().plot(kind='bar', figsize=(20,4))
df.resample('M').count().plot(y='date', kind='bar',figsize=(20,4))
Out[30]:
<matplotlib.axes._subplots.AxesSubplot at 0x1ef8fc50>
In [31]:
# 90 degree is east
ax = WindroseAxes.from_ax()
viridis = plt.get_cmap('viridis')
ax.bar(df.dir_windrose, df.speed, normed=True, opening=0.8, edgecolor='white', nsector=36, cmap=viridis)
ax.set_legend()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook.py:136: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)
In [32]:
if len(df) > 1000000:
    bins=arange(0,362)
    df['dir'].hist(bins=bins, normed=True,alpha=0.5,label='min')
    
    df = df_all_years.sample(n=500000, replace=True)    
    df['dir'].hist(bins=bins, normed=True,alpha=0.5,label='min resmapled')
    plt_configure(legend=True, figsize=(20,4))
In [33]:
x, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(df.speed)

# 1. Histogram comparison
fig = plt.figure()
df['speed'].hist(bins=arange(0, df.speed.max()), alpha=0.5, label='Data', normed=True)             
plot(x, y_weibull, '-', color='black',label='Weibull')   
plt_configure(figsize=(4,3),xlabel='V',ylabel='PDF', legend=True)

# 2. CDF comparison
fig = plt.figure()
plot(log(x), log(-log(1-y_ecdf)),'o', label='ECDF')
plot(log(x), log(-log(1-y_cdf_weibull)),'-', label='Weibull')
plt_configure(xlabel="ln(V)", ylabel="ln(-ln(1-P)",legend={'loc':'best'}, figsize=(4,3))
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:11: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:12: RuntimeWarning: divide by zero encountered in log
In [34]:
df.plot(kind='scatter', x='x', y='y', alpha=0.05, s=2)
plt.gca().set_aspect('equal')
plt_configure(figsize=(3.2,3.2))

2.2. Overview by Direction

In [35]:
if len(effective_column) == 16:
    rebinned_angle = 22.5
else: 
    rebinned_angle = 10
In [36]:
original_incre, incre = SECTOR_LENGTH, rebinned_angle
start, end = -original_incre/2 + incre/2, 360

max_speed = df.speed.max()
max_count = max_count_for_angles(df, start, end, incre)
plot_range = [0, max_speed, 0, max_count*1.05]

for angle in arange(start, end, incre):
    start_angle, end_angle = angle-incre/2, angle+incre/2
    sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)   
    
    fig = plt.figure()
    sub_df['speed'].hist(bins=arange(0, max_speed), alpha=0.5, label='Data')
    title ='%s (%s - %s), %s' % (angle, start_angle, end_angle, len(sub_df)) 
    plt.axis(plot_range)
    plt_configure(figsize=(3,1.5), title=title)
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py:524: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  max_open_warning, RuntimeWarning)

2.3 Overview by Month

In [37]:
month_incre = 1
current_df = df.query('speed>=1')
for month in arange(1, 12+month_incre, month_incre): 
    end_month = month+month_incre
    sub_df = current_df.query('(month >= @month) and (month < @end_month)')
    if len(sub_df) > 0:
        if month_incre == 1:
            title = 'Month: %s' % (month)
        else:
            title = 'Month: %s - %s ' % (month, end_month-1)
        ax = WindroseAxes.from_ax()
        ax.bar(sub_df.dir_windrose, sub_df.speed, normed=True, opening=0.8, edgecolor='white', nsector=36, cmap=plt.get_cmap('viridis'))
        plt_configure(figsize=(3,3), title=title)
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\cbook.py:136: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead.
  warnings.warn(message, mplDeprecation, stacklevel=1)

3. Create input data and configuration

In [38]:
SPEED_SET = array(list(zip(df.x, df.y)))
NUMBER_OF_GAUSSIAN = 3
FIT_METHOD = 'square_error'
DEFAULT_BANDWDITH = 1.5 if knot_unit else 0.7
fig_list = []
In [39]:
fit_limit = ceil(df['speed'].quantile(.95))
fitting_axis_range = arange(-fit_limit, fit_limit+1, 1)
print(fitting_axis_range)

FITTING_RANGE = []
for i in fitting_axis_range:
    for j in fitting_axis_range:
        FITTING_RANGE.append([i,j])
[-19 -18 -17 -16 -15 -14 -13 -12 -11 -10  -9  -8  -7  -6  -5  -4  -3  -2
  -1   0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16
  17  18  19]
In [40]:
plot_limit = ceil(df['speed'].quantile(.95))
PLOT_AXIS_RANGE = arange(-plot_limit, plot_limit+1, 1)

4. Kernel Density Estimation

In [41]:
sample = SPEED_SET
KDE_KERNEL = 'gaussian'
# KDE_KERNEL, bandwidth = 'tophat', 1
In [42]:
%%time
from sklearn.grid_search import GridSearchCV
# from sklearn.model_selection import GridSearchCV  ## too slow

# The bandwidth value sometimes would be too radical
if knot_unit:
    bandwidth_range = arange(0.7,2,0.2)
else:
    bandwidth_range = arange(0.4,1,0.1)

# Grid search is unable to deal with too many data (a long time is needed)
if len(sample) > 50000:    
    df_resample=df.sample(n=50000, replace=True)
    bandwidth_search_sample = array(list(zip(df_resample.x, df_resample.y)))
else:
    bandwidth_search_sample = sample

grid = GridSearchCV(neighbors.KernelDensity(kernel = KDE_KERNEL),
                    {'bandwidth': bandwidth_range}, n_jobs=-1, cv=4) 

grid.fit(bandwidth_search_sample)
bandwidth = grid.best_params_['bandwidth']
print(bandwidth)
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\cross_validation.py:44: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
  "This module will be removed in 0.20.", DeprecationWarning)
D:\ProgramData\Anaconda3\lib\site-packages\sklearn\grid_search.py:43: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.
  DeprecationWarning)
1.7
Wall time: 2min 4s
In [43]:
if 'bandwidth' not in globals():
    bandwidth = DEFAULT_BANDWDITH

kde = neighbors.KernelDensity(bandwidth=bandwidth,kernel = KDE_KERNEL).fit(sample)

points = FITTING_RANGE
# very slow if the dataset is too large, e.g. 100,000
# kde returns log prob, need to convert it
kde_result = exp(kde.score_samples(points))
print('bandwidth:', bandwidth, len(kde_result))
print(kde_result[:5])
bandwidth: 1.7 1521
[  4.31674156e-05   6.08207378e-05   8.15127765e-05   1.01431699e-04
   1.16815737e-04]
In [44]:
# Plot jPDF
X = Y = PLOT_AXIS_RANGE
# Can't work if pass as generate_Z_from_X_Y(X,Y, exp(kde.score_samples())), need to use lambda
# see http://stackoverflow.com/questions/21035437/passing-a-function-as-an-argument-in-python
kde_Z = generate_Z_from_X_Y(X,Y, lambda coords: exp(kde.score_samples(coords)))
colorbar_lim = 0, kde_Z.max()

plot_3d_prob_density(X,Y,kde_Z)

fig_kde,ax1 = plt.subplots(figsize=(4,3))
plot_2d_prob_density(X,Y,kde_Z,xlabel='x', ylabel='y',ax=ax1)

with sns.axes_style({'axes.grid' : False}):
    from matplotlib import ticker
    fig_hist,ax2 = plt.subplots(figsize=(4,3))
    _,_,_,image = ax2.hist2d(df.x, df.y, bins=PLOT_AXIS_RANGE, cmap='viridis',)
    ax2.set_aspect('equal')
    cb = plt.colorbar(image)
    tick_locator = ticker.MaxNLocator(nbins=6)
    cb.locator = tick_locator
    cb.update_ticks()
    plt_configure(ax=ax2, xlabel='x',ylabel='y')
align_figures()
In [45]:
kde_cdf = cdf_from_pdf(kde_result)

5. GMM by Expectation-maximization

In [46]:
sample= SPEED_SET
clf = mixture.GaussianMixture(n_components=NUMBER_OF_GAUSSIAN, covariance_type='full')
clf.fit(sample)
print(clf.converged_)
True
In [47]:
gmm_em_result = read_gmm_em_result(clf)
pretty_print_gmm(gmm_em_result)
Out[47]:
weight mean_x mean_y sig_x sig_y corr
1 0.354 1.634 -4.361 4.881 4.791 0.048
2 0.332 0.300 5.016 6.122 5.106 0.028
3 0.314 -7.680 -7.056 5.994 6.903 -0.136
In [48]:
fig,ax = plt.subplots(figsize=(3.5,3.5))
plot_gmm_ellipses(gmm_em_result, ax=ax)
GMM Plot Result
0.353853035122 [[ 1.63360499 -4.36116547]] [ 4.70974237  4.95960626] -55.4961219744
0.332169911043 [[ 0.29976059  5.01636921]] [ 5.09996849  6.12773995] -85.6445519312
0.313977053835 [[-7.68001161 -7.05552528]] [ 5.8031221   7.06430949] -158.124056048
In [49]:
X = Y = PLOT_AXIS_RANGE
pdf_Z = generate_Z_from_X_Y(X,Y, lambda coords: exp(clf.score_samples(coords)))

def residule_between_kde_and_gmm(points):
    kde_vals = exp(kde.score_samples(points))
    gmm_vals = exp(clf.score_samples(points))
    return kde_vals - gmm_vals 

residual_Z = generate_Z_from_X_Y(X,Y, residule_between_kde_and_gmm)

plot_3d_prob_density(X,Y,pdf_Z)
plot_3d_prob_density(X,Y,residual_Z)
align_figures()

fig = plt.figure(figsize=(4,3))
plot_2d_prob_density(X,Y,kde_Z,xlabel='x',ylabel='y', colorbar_lim=colorbar_lim)
fig_em = plt.figure(figsize=(4,3))
plot_2d_prob_density(X,Y,pdf_Z,xlabel='x',ylabel='y', colorbar_lim=colorbar_lim)
fig = plt.figure(figsize=(4,3))
plot_2d_prob_density(X,Y,residual_Z,xlabel='x',ylabel='y')
align_figures()

Goodness-of-fit Statistics

In [50]:
points = FITTING_RANGE
gmm_pdf_result = exp(clf.score_samples(points))
gof_df(gmm_pdf_result, kde_result)
Out[50]:
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.981 0.018 0.020 1.065330e-08 0.030 0.161

6. GMM by Optimization

In [51]:
sample = SPEED_SET
points = FITTING_RANGE
max_speed = df.speed.max()
print(FIT_METHOD)
square_error
In [52]:
# from GMM,EM 
# GMM format: weight, meanx, meany, sigx, sigy, rho
x0 = gmm_em_result

cons = [
        # sum of every 6th element, which is the fraction of each gaussian
        {'type': 'eq', 'fun': lambda x: sum(x[::6]) - 1},
        # # limit the width/height ratio of elliplse, optional
#         {'type': 'ineq', 'fun': lambda x: width_height_ratios_set(x) - 1/3},
#         {'type': 'ineq', 'fun': lambda x: 3 - width_height_ratios_set(x)},
]

bonds = [(0., 0.99),(-fit_limit, fit_limit),(-fit_limit, fit_limit),
         (0., fit_limit),(0., fit_limit),(-0.99, 0.99)]*(len(x0)//6)

result = sp.optimize.minimize(
    lambda x0: GMM_fit_score(x0, kde_result, points, FIT_METHOD),
    x0,
    bounds = bonds,
    constraints=cons,
    tol = 0.000000000001,
    options = {"maxiter": 500})
result
Out[52]:
     fun: -19.044975310422014
     jac: array([  9.67281580e-01,   0.00000000e+00,   0.00000000e+00,
         0.00000000e+00,   2.38418579e-07,  -2.38418579e-07,
         9.67279434e-01,  -2.38418579e-07,   2.38418579e-07,
         2.38418579e-07,   0.00000000e+00,   7.15255737e-07,
         9.67282057e-01,   0.00000000e+00,   0.00000000e+00,
         2.38418579e-07,  -2.38418579e-07,   0.00000000e+00,
         0.00000000e+00])
 message: 'Optimization terminated successfully.'
    nfev: 1094
     nit: 54
    njev: 54
  status: 0
 success: True
       x: array([ 0.37014097,  0.03232879,  4.688158  ,  7.07376277,  4.75022038,
        0.11992487,  0.51516257, -3.39477739, -6.68117635,  7.78493369,
        5.99107265,  0.08412117,  0.11469646,  1.74952584, -3.74672349,
        3.94575209,  3.00439036,  0.35870218])

6.1 GMM Result

In [53]:
gmm = group_gmm_param_from_gmm_param_array(result.x, sort_group = True)
mixed_model_pdf = generate_gmm_pdf_from_grouped_gmm_param(gmm)
gmm_pdf_result = mixed_model_pdf(points)
pretty_print_gmm(gmm)
Out[53]:
weight mean_x mean_y sig_x sig_y corr
1 0.515 -3.395 -6.681 7.785 5.991 0.084
2 0.370 0.032 4.688 7.074 4.750 0.120
3 0.115 1.750 -3.747 3.946 3.004 0.359
In [54]:
fig_gmm, ax = plt.subplots(figsize=(3.5,3.5))
plot_gmm_ellipses(gmm,ax=ax)
GMM Plot Result
0.51516257396 [[-3.39477739 -6.68117635]] [ 5.94011857  7.82388238] -81.1919373945
0.370140967018 [[ 0.03232879  4.688158  ]] [ 4.68889421  7.11456144] -81.8254212909
0.114696459022 [[ 1.74952584 -3.74672349]] [ 2.63299605  4.20269589] -63.7856805013

6.2 Goodness-of-fit statistics

In [55]:
gof_df(gmm_pdf_result, kde_result)
Out[55]:
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.014 0.025 5.356392e-09 0.021 0.114
In [56]:
X = Y = PLOT_AXIS_RANGE
pdf_Z = generate_Z_from_X_Y(X,Y, mixed_model_pdf)# passing a function as an argument

def residule_between_kde_and_gmm(points):
    kde_vals = exp(kde.score_samples(points))
    gmm_vals = mixed_model_pdf(points)
    return kde_vals - gmm_vals 

residual_Z = generate_Z_from_X_Y(X,Y, residule_between_kde_and_gmm)

plot_3d_prob_density(X,Y,pdf_Z)
plot_3d_prob_density(X,Y,residual_Z)
align_figures()

fig = plt.figure(figsize=(4,3))
plot_2d_prob_density(X,Y,kde_Z,xlabel='x',ylabel='y')
fig_gmm = plt.figure(figsize=(4,3))
plot_2d_prob_density(X,Y,pdf_Z,xlabel='x',ylabel='y')
fig = plt.figure(figsize=(4,3))
plot_2d_prob_density(X,Y,residual_Z,xlabel='x',ylabel='y')
align_figures()
In [57]:
def f(V,theta):
    return (mixed_model_pdf([[V*cos(theta),V*sin(theta)]]))*V
In [58]:
x, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(df.speed)

# 3. GMM distribution
y_ = [integrate.nquad(f, [[0, x_val],[0, 2*pi]]) for x_val in x]
y_cdf_gmm = array(list(zip(*y_))[0])

plot(log(x), log(-log(1-y_ecdf)),'o', label = 'Empirical')
plot(log(x), log(-log(1-y_cdf_weibull)),'--', label = 'Weibull')
plot(log(x), log(-log(1-y_cdf_gmm)),'-', color='black', label = 'GMM')
plt_configure(xlabel='ln(V)',ylabel='ln(-ln(1-P))',legend={'loc':'best'})
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:7: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:8: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:9: RuntimeWarning: divide by zero encountered in log
In [59]:
# Calculate Speed Distribution
# 1. GMM Model
x = arange(0, max_speed, 0.5)
y_ =[integrate.nquad(f, [[x_-0.01, x_+0.01],[0, 2*pi]]) for x_ in x]
y_gmm = array(list(zip(*y_))[0])*len(df.speed)/0.02

# 2. Weibull
y_weibul = sp.stats.weibull_min.pdf(x, *weibull_params)

df['speed'].hist(bins=arange(0, df.speed.max()), alpha=0.5, label='Data')
plot(x, y_gmm,'-', color='black', label='GMM')
plot(x, y_weibul*len(df.speed), '--', color='black', label='Weibull') 
print('Speed Distribution Comparison')
plt_configure(xlabel='Speed',ylabel='Frequency',legend=True, figsize=(4.5, 2))
plt.gca().set_ylim(bottom = 0)
plt.locator_params(axis='y', nbins=5)
Speed Distribution Comparison
In [60]:
# Calculate Angle Distribution
x = linspace(0,2*pi, num=36+1)
y_ =[integrate.nquad(f, [[0, inf],[x_-pi/36, x_+pi/36]]) for x_ in x]
y = array(list(zip(*y_))[0])*len(df['dir']) 

df['dir'].hist(bins=DIR_BIN, alpha=0.5, label='Data')
plot(x/pi*180, y,'-', color='black', label='GMM')
title='Direction Distribution Comparison'
plt_configure(xlabel='Direction',ylabel='Frequency', 
              legend={'loc': 'best'} ,tight='xtight',figsize = (4.5,2))
dir_fig = plt.gcf()
print(title)
Direction Distribution Comparison
In [61]:
# %%time
incre = max(SECTOR_LENGTH, 10)
density_collection=Parallel(n_jobs=-1)(delayed(direction_compare)(gmm, df, angle, incre) 
                                        for angle in arange(0, 360, incre))  
# This R square is computed as in paper 
# Comparison of bivariate distribution constructionapproaches for analysing wind speed anddirection data
# http://onlinelibrary.wiley.com/doi/10.1002/we.400/full
print(true_R_square(density_collection))
0.904079721232

6.3 Sectoral Comaprison

In [62]:
# Calculate Speed Distribution
def model_data_comparison(df, original_incre = 10, incre = 10):
    start, end = -original_incre/2 + incre/2, 360
    max_diff_array = []
    curve_collection = []
    max_speed = df.speed.max()
    
    # Find a max count for plotting histogram
    max_count = max_count_for_angles(df, start, end, incre)
    plot_range = [0, max_speed, 0, max_count*1.05]
    
    for angle in arange(start, end, incre):
        angle_radian, incre_radian = radians(angle), radians(incre)  
        start_angle, end_angle = angle-incre/2, angle+incre/2
        
        # Select data from observation
        sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)
        data_size = len(sub_df.speed)
        # 1. Get Weibull and ECDF
        x, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(sub_df.speed)
        # 2. Get GMM PDF, CDF
        _, y_gmm, y_cdf_gmm, direction_prob = gmm_integration_in_direction(f, angle_radian-incre_radian/2, angle_radian+incre_radian/2, x)
        
        # 3. Make Plots
        fig = plt.figure(figsize=(13,1.3))
        # 3.1. Frequency Comparison
        ax1 = fig.add_subplot(1,3,1)        
        sub_df['speed'].hist(bins=arange(0, sub_max_speed), alpha=0.5, label='Data')                  
        plot(x, y_gmm*data_size,'-', color='black', label='GMM')
        plot(x, y_weibull*data_size, '--', color='black',label='Weibull')   
        plt_configure(xlabel = "V", ylabel='Frequency', legend=True)
        plt.axis(plot_range)
        
        # 3.2. CDF Comaprison
        ax2 = fig.add_subplot(1,3,2)
        plot(x, y_ecdf,'o', alpha=0.8, label='Data')
        plot(x, y_cdf_gmm,'-', color='black',label='GMM')
        plot(x, y_cdf_weibull,'--', color='black',label='Weibull')
        plt.gca().set_xlim(right = max_speed)
        plt_configure(xlabel = "V", ylabel='P', legend=True)
        
        # 3.3. Weibull Comparison
        ax3 = fig.add_subplot(1,3,3)
        plot(log(x), log(-log(1-y_ecdf)),'o', alpha=0.8, label='Data')
        plot(log(x), log(-log(1-y_cdf_gmm)),'-', color='black', label='GMM')
        plot(log(x), log(-log(1-y_cdf_weibull)),'--',color='black',label='Weibull')
        plt.gca().set_xlim(right = log(max_speed+1))
        plt_configure(xlabel="ln(V)", ylabel="ln(-ln(1-P)",legend={'loc':'best'})
        
        bins = arange(0, sub_df.speed.max()+1)
        density, _ = np.histogram(sub_df['speed'], bins=bins, normed=True)
        density_expected_ =[integrate.nquad(f, [[x_, x_+1],[angle_radian-incre_radian/2, angle_radian+incre_radian/2]]) 
                            for x_ in bins[:-1]]
        density_expected_gmm = array(list(zip(*density_expected_ ))[0])/direction_prob
        R_square_gmm = sector_r_square(density, density_expected_gmm)
        
        density_expected_weibull = sp.stats.weibull_min.cdf(bins[1:], *weibull_params) - sp.stats.weibull_min.cdf(bins[:-1], *weibull_params) 
        R_square_weibull = sector_r_square(density, density_expected_weibull)

        diff, diff_weibull= np.abs(y_ecdf - y_cdf_gmm), np.abs(y_ecdf - y_cdf_weibull)
        max_diff_array.append([len(sub_df), angle, diff.max(), x[diff.argmax()], 
                               diff_weibull.max(), x[diff_weibull.argmax()], R_square_gmm, R_square_weibull])
        curves = {'angle': angle, 'data_size': data_size, 'weight': direction_prob, 
                  'x': x, 'gmm_pdf': y_gmm, 'gmm_cdf': y_cdf_gmm,
                  'weibull_pdf': y_weibull, 'weibull_cdf': y_cdf_weibull, 'ecdf': y_ecdf}
        curve_collection.append(curves)
        
        plt.show()
        print('%s (%s - %s) degree' % (angle, start_angle, end_angle))
        print('data size:', len(sub_df), 'weight', len(sub_df)/len(df))
        print('GMM', 'Weibull')
        print('R square', R_square_gmm,  R_square_weibull)
        print('max diff:', diff.max(), diff_weibull.max(), 'speed value:', x[diff.argmax()], 'y gmm', y_cdf_gmm[diff.argmax()])
        print(' ')
    return max_diff_array, curve_collection
In [63]:
%%time
if len(effective_column) == 16:
    rebinned_angle = 22.5
else: 
    rebinned_angle = 20
max_diff_array, curve_collection = model_data_comparison(df, SECTOR_LENGTH, rebinned_angle)
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:44: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:45: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:46: RuntimeWarning: divide by zero encountered in log
5.0 (-5.0 - 15.0) degree
data size: 1023 weight 0.0234487817177436
GMM Weibull
R square 0.906775308525 0.962704048792
max diff: 0.0993643242462 0.0166035291378 speed value: 10.0994250662 y gmm 0.696334600485
 
25.0 (15.0 - 35.0) degree
data size: 1789 weight 0.04100671602448025
GMM Weibull
R square 0.84189478037 0.979203391696
max diff: 0.120597169704 0.0152948329595 speed value: 9.87448852138 y gmm 0.59097354019
 
45.0 (35.0 - 55.0) degree
data size: 2002 weight 0.0458890136841864
GMM Weibull
R square 0.895032911381 0.977413809983
max diff: 0.093219439374 0.0158924841621 speed value: 10.3253169724 y gmm 0.618568772414
 
65.0 (55.0 - 75.0) degree
data size: 2170 weight 0.049739840007334904
GMM Weibull
R square 0.941658987869 0.954505070832
max diff: 0.0363216621727 0.0260034857714 speed value: 7.33991198513 y gmm 0.408378798657
 
85.0 (75.0 - 95.0) degree
data size: 2057 weight 0.0471497008733124
GMM Weibull
R square 0.869674645515 0.905942717285
max diff: 0.0636941605047 0.0384944458197 speed value: 13.3912803352 y gmm 0.904724787632
 
105.0 (95.0 - 115.0) degree
data size: 1777 weight 0.04073165700139822
GMM Weibull
R square 0.92150184219 0.915454403197
max diff: 0.0519541119324 0.036921452578 speed value: 14.5452980117 y gmm 0.947846064662
 
125.0 (115.0 - 135.0) degree
data size: 1540 weight 0.035299241295528
GMM Weibull
R square 0.902181979962 0.928922448736
max diff: 0.0799048816112 0.0243914008248 speed value: 9.32929636112 y gmm 0.630554232261
 
145.0 (135.0 - 155.0) degree
data size: 2037 weight 0.04669126916817567
GMM Weibull
R square 0.925151787866 0.956900303994
max diff: 0.0553719722956 0.0540120392554 speed value: 11.9106863009 y gmm 0.775261311946
 
165.0 (155.0 - 175.0) degree
data size: 2028 weight 0.046484974900864146
GMM Weibull
R square 0.936251807438 0.950951735023
max diff: 0.0476619654629 0.0426545538583 speed value: 4.95766280282 y gmm 0.190659993076
 
185.0 (175.0 - 195.0) degree
data size: 2424 weight 0.055561922662571345
GMM Weibull
R square 0.930932557836 0.958258347862
max diff: 0.0402052795307 0.0645022351962 speed value: 6.46465211413 y gmm 0.256376896692
 
205.0 (195.0 - 215.0) degree
data size: 2915 weight 0.06681642102367799
GMM Weibull
R square 0.954909212719 0.977268335322
max diff: 0.0478037300908 0.0385409175437 speed value: 15.3189482113 y gmm 0.720635377971
 
225.0 (215.0 - 235.0) degree
data size: 4440 weight 0.10177183854035345
GMM Weibull
R square 0.965848426722 0.972975760176
max diff: 0.0223363029289 0.0257574939163 speed value: 7.09321789887 y gmm 0.225039005632
 
245.0 (235.0 - 255.0) degree
data size: 4422 weight 0.1013592500057304
GMM Weibull
R square 0.977436129431 0.979782217914
max diff: 0.0213768426862 0.0149495786118 speed value: 9.24367474233 y gmm 0.41620796057
 
265.0 (255.0 - 275.0) degree
data size: 3553 weight 0.0814403924175396
GMM Weibull
R square 0.93577848671 0.960659059289
max diff: 0.0567055946639 0.0177262099086 speed value: 7.20393654252 y gmm 0.338453425882
 
285.0 (275.0 - 295.0) degree
data size: 2924 weight 0.06702271529098952
GMM Weibull
R square 0.938884969733 0.957855135444
max diff: 0.0574549610174 0.0296846277835 speed value: 6.42759775842 y gmm 0.334131906288
 
305.0 (295.0 - 315.0) degree
data size: 2550 weight 0.05845004240493273
GMM Weibull
R square 0.940717910535 0.957884314848
max diff: 0.0542613510195 0.0197344681523 speed value: 12.115127353 y gmm 0.789268060745
 
325.0 (315.0 - 335.0) degree
data size: 2112 weight 0.0484103880624384
GMM Weibull
R square 0.963032264335 0.968383696218
max diff: 0.043893016406 0.0165968597963 speed value: 8.28310775234 y gmm 0.591050165412
 
345.0 (335.0 - 355.0) degree
data size: 1494 weight 0.03424484837371353
GMM Weibull
R square 0.934905453425 0.951859727035
max diff: 0.0639380994741 0.110124849427 speed value: 12.0434476089 y gmm 0.844361766657
 
Wall time: 1min 1s
In [64]:
diff_df = pd.DataFrame(max_diff_array,columns=['datasize','direction', 'gmm', 'speed_gmm',
                                               'weibull', 'speed_weibull', 'r_square_gmm', 'r_square_weibull'])  

gmm_mean, weibull_mean = plot_sectoral_comparison(diff_df.r_square_gmm, diff_df.r_square_weibull, diff_df.direction, diff_df.datasize)
plt_configure(ylabel="$\ R^2$")
ylim = min(plt.gca().get_ylim()[0],0.85)
plt.gca().set_ylim(top=1, bottom=ylim)
print(gmm_mean, weibull_mean)
0.9343790381086342 0.9596441603541828
In [65]:
gmm_mean, weibull_mean = plot_sectoral_comparison(diff_df.gmm, diff_df.weibull, diff_df.direction, diff_df.datasize)
plt_configure(ylabel="K-S")
ylim = max(plt.gca().get_ylim()[1],0.15)
plt.gca().set_ylim(top=ylim, bottom=0)
print(gmm_mean, weibull_mean)
0.052367472443602105 0.03144751048756332
In [66]:
# Compare direction weight with previous figure
display(dir_fig)

6.4 Insufficient-fit Sector Investigation

6.4.1 Data Variability, by Bootstrap (Resampling)

In [67]:
max_diff_element = max(max_diff_array, key=lambda x: x[2])
angle =  max_diff_angle = max_diff_element[1]
incre = rebinned_angle
In [68]:
FRACTION = 1

# Select data from observation
start_angle, end_angle = angle-incre/2, angle+incre/2
angle_radian, incre_radian = radians(angle), radians(incre)  
sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)
# weibull_params = sp.stats.weibull_min.fit(sub_df.speed, loc=0)
In [69]:
x = arange(0, sub_max_speed, 0.5)
_, y_weibull, y_cdf_weibull, weibull_params, y_ecdf = fit_weibull_and_ecdf(sub_df.speed, x)
_, y_gmm, y_cdf_gmm, direction_prob = gmm_integration_in_direction(f, angle_radian-incre_radian/2, angle_radian+incre_radian/2, x)

fig = plt.figure(figsize=(13,1.5))
ax1 = fig.add_subplot(1,3,1)   
ax2 = fig.add_subplot(1,3,2)   
ax3 = fig.add_subplot(1,3,3)   

# 1. Data
bins=arange(0, sub_max_speed)
sub_df['speed'].hist(ax=ax1, bins=bins, alpha=0.5, label='Data', normed=True)  

# 2. GMM
ax1.plot(x, y_gmm,'-', color='black', label='GMM')
ax2.plot(x, y_cdf_gmm,'-', color = 'black', label='GMM')
ax3.plot(log(x), log(-log(1-y_cdf_gmm)),'-', color = 'black',label='GMM')

# 3. Weilbull 
ax1.plot(x, y_weibull,'--',color='black',label='Weibull')
ax2.plot(x, y_cdf_weibull,'--',label='Weibull')
ax3.plot(log(x), log(-log(1-y_cdf_weibull)),'--',label='Weibull')

# 4. Data Resampled
count_collection = []
for i in range(1,100):
    sub_df_resampled = sub_df.sample(frac=FRACTION, replace=True)    
    resampled_count, _ = np.histogram(sub_df_resampled['speed'], bins=bins, normed=True) 
    count_collection.append(resampled_count)
    
    ecdf = sm.distributions.ECDF(sub_df_resampled.speed)
    y_ecdf = ecdf(x) 
    ax2.plot(x, y_ecdf,':', label='Data Resampled')
    ax3.plot(log(x), log(-log(1-y_ecdf)),':', label='Data Resampled')
    if i == 1: 
        plt_configure(ax=ax2, xlabel='V',ylabel='P',legend={'loc':'best'})
        plt_configure(ax=ax3, xlabel='V',ylabel='ln(-ln(1-P)',legend={'loc':'best'})

print('%s (%s - %s) Degree Speed Distribution' % (angle, start_angle, end_angle))
count_collection = np.array(count_collection)
mx, mn = np.max(count_collection,0), np.min(count_collection,0)
ax1.plot(bins[1:]-0.5, mx, ':', color='blue')
ax1.plot(bins[1:]-0.5, mn, ':', color='blue', label='Resample limit')
ax1.set_ylim(bottom = 0)
plt_configure(ax=ax1, xlabel='V',ylabel='Frequency',legend={'loc':'best'})
ax1.locator_params(axis='y', nbins=5)
ax2.locator_params(axis='y', nbins=5)
ax3.locator_params(axis='y', nbins=5)

diff = abs(y_ecdf - y_cdf_gmm)
print(diff.max(), x[diff.argmax()], y_cdf_gmm[diff.argmax()])
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:17: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:22: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:34: RuntimeWarning: divide by zero encountered in log
25.0 (15.0 - 35.0) Degree Speed Distribution
0.137236141174 10.0 0.600047257373

6.4.2 Time Variability

In [70]:
fig_time_variability_3d = plt.figure()
ax1 = fig_time_variability_3d.gca(projection='3d')

fig_time_variability_cdf,ax2 = plt.subplots(figsize=(3,1.8))
fig_time_variability_weibull, ax3 = plt.subplots(figsize=(3,1.8))

ax2.plot(x, y_cdf_gmm,'-', color='black', label = 'GMM')
ax2.plot(x, y_cdf_weibull,'--', label='Weibull')

ax3.plot(log(x), log(-log(1-y_cdf_gmm)),'-', color='black',label='GMM')
ax3.plot(log(x), log(-log(1-y_cdf_weibull)), '--', label='Weibull')

# 3. Data
prop_cycle=iter(mpl.rcParams['axes.color_cycle'])
for start_time in range(20000000, 20150000, 50000):
    end_time = start_time + 50000 
    time_label = start_time//10000
    df_other_years = df_all_years.query('(date >= @start_time) & (date < @end_time)')
    df_other_years_at_angle, sub_max_speed_other_year = select_df_by_angle(df_other_years, start_angle, end_angle)
    if len(df_other_years_at_angle) > 0 :
        
        ecdf = sm.distributions.ECDF(df_other_years_at_angle.speed)
        y_ecdf = ecdf(x)
        ax2.plot(x, y_ecdf,':', label = time_label)
        ax3.plot(log(x), log(-log(1-y_ecdf)),':', label = time_label)
        
        title = '%s - %s' %(time_label, time_label+4)
        count, division = np.histogram(df_other_years_at_angle['speed'], normed=True,
                                       bins=arange(0, sub_max_speed_other_year))
        ax1.bar(left=division[:-1], height=count, zs=time_label, zdir='x', 
                color=next(prop_cycle), alpha=0.8)
        x_3d = time_label*np.ones_like(x)
        ax1.plot(x_3d, x, y_gmm, '-', color='black', label='GMM'  if time_label == 2010 else '')
        ax1.plot(x_3d, x, y_weibull, '--', color='blue', label='Weibull' if time_label == 2010 else '')
        
print('%s (%s - %s) Degree Speed Distribution' % (angle, start_angle, end_angle))
ax1.set_ylim(bottom = 0)
ax1.set_zlabel('Frequency')
plt_configure(ax=ax1, xlabel='Time',ylabel='V', legend=True)
plt_configure(ax=ax2, xlabel='V',ylabel='P',legend={'loc':'best'})
plt_configure(ax=ax3, xlabel="ln(V)", ylabel="ln(-ln(1-P)",legend={'loc':'best'})
ax1.set_zlim(bottom = 0)
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:10: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:11: RuntimeWarning: divide by zero encountered in log
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
D:\ProgramData\Anaconda3\lib\site-packages\ipykernel\__main__.py:25: RuntimeWarning: divide by zero encountered in log
25.0 (15.0 - 35.0) Degree Speed Distribution

6.4.3 Adjacent Sector Variability

In [71]:
incre = rebinned_angle
angle_group = [max_diff_angle-incre, max_diff_angle, max_diff_angle+incre]
In [72]:
fig_adjecent_variability_3d = plt.figure()
ax1 = fig_adjecent_variability_3d.gca(projection='3d')
fig_adjecent_variability_cdf, ax2 = plt.subplots(figsize=(3,1.8))
fig_adjecent_variability_weibull, ax3 = plt.subplots(figsize=(3,1.8))

legend_3d = False
prop_cycle=iter(mpl.rcParams['axes.color_cycle'])

curve_df = pd.DataFrame(curve_collection)

for angle in angle_group:
    curves = curve_df.query('angle == @angle%360').T.to_dict()
    curves = curves[list(curves)[0]]
    data_size, x =  curves['data_size'], curves['x']
    y_gmm, y_cdf_gmm =  curves['gmm_pdf'], curves['gmm_cdf'] 
    y_weibull, y_cdf_weibull, y_cdf = curves['weibull_pdf'],  curves['weibull_cdf'], curves['ecdf']

    linestyle = '-' if angle == max_diff_angle else ':'
    alpha = 0.7 if angle == max_diff_angle else 0.3

    ax2.plot(x, y_gmm*data_size, linestyle, label=angle)        
    ax3.plot(x, y_weibull*data_size, linestyle, label=angle)

    start_angle, end_angle = angle-incre/2, angle+incre/2
    sub_df, sub_max_speed = select_df_by_angle(df, start_angle, end_angle)

    x_3d = angle*np.ones_like(x)
    ax1.plot(x_3d, x, y_gmm*data_size, color='black', label='GMM')
    ax1.plot(x_3d, x, y_weibull*data_size, color='blue', linestyle='--',label='Weibull')

    count, division = np.histogram(sub_df['speed'], bins=arange(0, sub_max_speed))
    ax1.bar(left=division[:-1], height=count, zs=angle, zdir='x', color=next(prop_cycle), alpha=0.8)

    if legend_3d == False:
        ax1.legend()
        legend_3d = True
        
plt_configure(ax=ax1, xlabel='Direction', ylabel='Speed')   
plt_configure(ax=ax2, xlabel='V',ylabel='Frequency',legend={'loc':'best'})
plt_configure(ax=ax3, xlabel='V',ylabel='Frequency',legend={'loc':'best'})
ax1.set_zlabel('Frequency')
ax1.set_zlim(bottom = 0)
ylim = max(ax1.get_ylim()[1],ax3.get_ylim()[1])
ax2.set_ylim(bottom = 0, top=ylim)
ax3.set_ylim(bottom = 0, top=ylim)

print(max_diff_angle) 
print('GMM, Weibull, Histogram')
align_figures()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
25.0
GMM, Weibull, Histogram

7. Result Variability & Cross-Validation

In [73]:
if 'bandwidth' not in globals():
    bandwidth = DEFAULT_BANDWDITH    
if 'FIT_METHOD' not in globals():
    FIT_METHOD = 'square_error'       
if 'KDE_KERNEL' not in globals():
    KDE_KERNEL = 'gaussian'
    
config = {'bandwidth': bandwidth, 
          'fitting_range': FITTING_RANGE,
          'fit_limit': fit_limit,
          'kde_kernel': KDE_KERNEL}

7.1 Variability of the Result

In [74]:
%%time
results = Parallel(n_jobs=-1)(delayed(resampled_fitting)(df, FIT_METHOD, NUMBER_OF_GAUSSIAN, config) for i in range(10))                        
for result in results:
    display(pretty_print_gmm(result['gmm']))
    fig,ax = plt.subplots(figsize=(3.5,3.5))
    plot_gmm_ellipses(result['gmm'],ax=ax)
    plt.show()
    
    display(gof_df(result['gmm_pdf_result'], result['kde_result']))
    display(gof_df(result['gmm_pdf_result'], kde_result))
    print('')
weight mean_x mean_y sig_x sig_y corr
1 0.484 -3.085 -6.996 7.783 5.786 0.141
2 0.400 -0.324 4.425 7.302 4.894 0.164
3 0.116 1.642 -3.631 3.935 2.984 0.376
GMM Plot Result
0.484228886123 [[-3.0845049  -6.99612589]] [ 5.66267631  7.87327375] -77.4578865038
0.40025266144 [[-0.32407742  4.4253307 ]] [ 4.77792898  7.37841905] -79.1468328236
0.115518452438 [[ 1.64202424 -3.63065276]] [ 2.58670327  4.20700752] -63.3577089507
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.014 0.026 5.567232e-09 0.021 0.116
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.014 0.025 5.645448e-09 0.022 0.117

weight mean_x mean_y sig_x sig_y corr
1 0.503 -3.299 -6.804 7.849 5.959 0.101
2 0.386 -0.017 4.519 7.148 4.885 0.138
3 0.112 1.630 -3.824 3.860 2.993 0.370
GMM Plot Result
0.502650111576 [[-3.29941044 -6.8037364 ]] [ 5.88824336  7.90219034] -80.0138386738
0.385570720165 [[-0.01669509  4.51942922]] [ 4.80029687  7.20560332] -80.281867194
0.111779168259 [[ 1.6299796  -3.82359501]] [ 2.59366675  4.13949302] -62.4111034651
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.014 0.024 5.671061e-09 0.022 0.118
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.012 0.024 5.427645e-09 0.021 0.115

weight mean_x mean_y sig_x sig_y corr
1 0.803 -2.734 -2.677 7.591 8.426 0.164
2 0.112 1.858 -4.060 3.909 2.978 0.366
3 0.085 2.998 5.165 4.466 3.153 -0.051
GMM Plot Result
0.80285599741 [[-2.73384409 -2.6771335 ]] [ 7.2023372   8.76074141] 151.263260652
0.112238402403 [[ 1.85783672 -4.0598027 ]] [ 2.59705729  4.17184972] -63.4821668231
0.0849056001871 [[ 2.998354    5.16453153]] [ 3.14523315  4.47118901] -94.0612626138
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.013 0.011 5.649899e-09 0.021 0.117
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.012 0.011 5.351947e-09 0.021 0.114

weight mean_x mean_y sig_x sig_y corr
1 0.487 -3.335 -7.085 7.727 5.612 0.103
2 0.400 -0.420 4.422 7.289 4.854 0.153
3 0.114 1.821 -3.652 3.883 2.998 0.367
GMM Plot Result
0.486640580214 [[-3.33513912 -7.08545722]] [ 5.55018197  7.77176742] -81.2420134052
0.399662957025 [[-0.4200076   4.42227455]] [ 4.75437029  7.35417425] -79.960625425
0.113696462761 [[ 1.82115036 -3.65220184]] [ 2.60596891  4.15626726] -62.7481702963
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.991 0.016 0.026 5.262407e-09 0.021 0.113
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.015 0.024 5.567014e-09 0.022 0.117

weight mean_x mean_y sig_x sig_y corr
1 0.803 -2.635 -2.592 7.591 8.434 0.167
2 0.114 1.382 -4.190 4.038 3.145 0.412
3 0.082 2.764 5.174 4.708 3.057 -0.100
GMM Plot Result
0.803444692442 [[-2.63549405 -2.59199281]] [ 7.19142404  8.77801394] 151.113038258
0.114449737092 [[ 1.38185275 -4.19020971]] [ 2.63781954  4.38571746] -60.7406574931
0.0821055704654 [[ 2.76418156  5.17426217]] [ 3.0307628   4.72488711] -96.3371823575
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.991 0.014 0.011 4.870996e-09 0.020 0.109
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.012 0.011 5.317373e-09 0.021 0.114

weight mean_x mean_y sig_x sig_y corr
1 0.797 -2.890 -2.754 7.601 8.459 0.156
2 0.117 1.915 -4.044 4.010 3.293 0.425
3 0.087 3.087 5.232 4.629 3.267 -0.046
GMM Plot Result
0.796644273261 [[-2.89002829 -2.75427139]] [ 7.24414709  8.7665133 ] 152.193366972
0.116843514181 [[ 1.91520692 -4.04403603]] [ 2.6961583  4.4333246] -57.5103274847
0.0865122125588 [[ 3.08733254  5.23157727]] [ 3.26038694  4.63367114] -93.6547208101
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.991 0.013 0.011 4.806923e-09 0.021 0.108
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.013 0.011 5.451823e-09 0.021 0.115

weight mean_x mean_y sig_x sig_y corr
1 0.808 -2.781 -2.818 7.478 8.330 0.151
2 0.103 1.898 -4.139 3.692 2.885 0.240
3 0.089 3.387 5.102 4.441 3.520 -0.121
GMM Plot Result
0.808361335611 [[-2.78145201 -2.8183921 ]] [ 7.14658074  8.61658477] 152.763194402
0.102538481956 [[ 1.89812624 -4.13933147]] [ 2.70042399  3.8292332 ] -68.035671268
0.0891001824331 [[ 3.38671252  5.10167767]] [ 3.45429285  4.49251662] -103.606042612
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.010 0.011 5.543876e-09 0.021 0.116
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.009 0.010 5.508467e-09 0.022 0.116

weight mean_x mean_y sig_x sig_y corr
1 0.526 -3.607 -6.459 7.776 6.110 0.063
2 0.351 0.374 4.838 6.882 4.682 0.069
3 0.123 1.736 -3.834 4.007 3.089 0.322
GMM Plot Result
0.525786428644 [[-3.6073124  -6.45945695]] [ 6.07918889  7.80031259] -82.7470006451
0.350865721076 [[ 0.37423506  4.8380124 ]] [ 4.66171719  6.8963039 ] -85.041723152
0.123347850281 [[ 1.73637777 -3.83429159]] [ 2.76672897  4.23547614] -64.6363086303
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.013 0.022 5.473331e-09 0.021 0.116
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.014 0.024 5.497827e-09 0.022 0.116

weight mean_x mean_y sig_x sig_y corr
1 0.777 -2.856 -2.639 7.645 8.554 0.184
2 0.140 1.806 -4.136 4.233 3.497 0.403
3 0.083 2.467 5.233 4.904 2.840 -0.012
GMM Plot Result
0.777391095039 [[-2.855868   -2.63858794]] [ 7.19179876  8.93765137] 150.759925074
0.140048944528 [[ 1.80585724 -4.1355827 ]] [ 2.90844551  4.65695492] -57.7259947798
0.0825599604329 [[ 2.46654348  5.23259358]] [ 2.83965284  4.90421632] -90.5772214184
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.991 0.013 0.011 5.195152e-09 0.021 0.113
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.014 0.011 5.300344e-09 0.021 0.114

weight mean_x mean_y sig_x sig_y corr
1 0.801 -2.702 -2.510 7.512 8.534 0.174
2 0.118 1.662 -4.153 4.156 3.127 0.373
3 0.081 3.218 5.216 4.581 3.117 -0.040
GMM Plot Result
0.801129072227 [[-2.70221875 -2.50967892]] [ 7.12753478  8.85792701] 153.168639457
0.118234272882 [[ 1.66185457 -4.15311774]] [ 2.71983162  4.43306347] -63.8654651846
0.0806366548917 [[ 3.21799523  5.21633722]] [ 3.11239469  4.58461496] -92.9039722442
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.990 0.014 0.012 5.264785e-09 0.021 0.113
R_square K_S Chi_square MSE RMSE / Max RMSE / Mean
0 0.991 0.013 0.010 5.248679e-09 0.021 0.113
Wall time: 33.9 s

7.2 Cross-validation, to select the number of Gaussian

In [75]:
%%time
from sklearn.cross_validation import train_test_split, KFold

## 5-fold cross validation
gaussian_number_range = arange(1,6)
CV_result_train_all,CV_result_test_all =[],[]
number_of_fold = 4
print('Number of train/test dataset', len(df)*(number_of_fold-1)/number_of_fold, len(df)/number_of_fold) 

for number_of_gaussian in gaussian_number_range:
    print( '  ')
    print('Number of gaussian', number_of_gaussian)
    
    kf = KFold(len(df), n_folds=number_of_fold, shuffle=True) 

    CV_result = Parallel(n_jobs=-1)(delayed(fit_per_fold)(df, train_index, test_index, FIT_METHOD, number_of_gaussian, config) for train_index, test_index in kf)                        

    CV_result_train, CV_result_test = list(zip(*CV_result))
    CV_result_train, CV_result_test = list(CV_result_train), list(CV_result_test)
        
    CV_result_train_all.append(CV_result_train)
    CV_result_test_all.append(CV_result_test)
    
    print('Train')
    pretty_pd_display(CV_result_train)
    print('Test')
    pretty_pd_display(CV_result_test)
Number of train/test dataset 32720.25 10906.75
  
Number of gaussian 1
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.027219 0.040464 2.898580e-08 0.049658 0.265733 0.947896
1 0.028245 0.041575 2.997655e-08 0.050170 0.270496 0.945545
2 0.027762 0.039714 2.960310e-08 0.049850 0.268611 0.946371
3 0.027415 0.040193 2.957141e-08 0.050093 0.268519 0.946423
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.033761 0.042753 3.403091e-08 0.053033 0.288401 0.937362
1 0.028423 0.043597 2.994977e-08 0.050585 0.269776 0.946506
2 0.027849 0.035940 2.873965e-08 0.049723 0.264845 0.948216
3 0.031244 0.040539 2.944106e-08 0.049517 0.267903 0.947061
  
Number of gaussian 2
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.021724 0.028673 1.038907e-08 0.029763 0.159188 0.981242
1 0.021623 0.027755 1.060801e-08 0.029667 0.160763 0.980848
2 0.021984 0.028614 1.055291e-08 0.029945 0.160421 0.980847
3 0.022753 0.030285 1.098735e-08 0.030498 0.163680 0.980099
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.023887 0.028277 1.197599e-08 0.031357 0.170769 0.978212
1 0.025686 0.027068 1.236976e-08 0.033030 0.173855 0.977530
2 0.025376 0.029655 1.266115e-08 0.032140 0.175641 0.977355
3 0.024451 0.031826 1.093320e-08 0.030282 0.163247 0.980320
  
Number of gaussian 3
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.028554 0.014345 5.381547e-09 0.021481 0.114611 0.990183
1 0.009855 0.012101 5.041395e-09 0.020732 0.110820 0.990870
2 0.025475 0.013927 5.323004e-09 0.020915 0.113861 0.990461
3 0.024901 0.013982 5.322744e-09 0.021236 0.113966 0.990364
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.030204 0.014063 7.509605e-09 0.024627 0.135084 0.986770
1 0.014457 0.012697 6.894495e-09 0.023796 0.129821 0.987577
2 0.029241 0.016023 7.829685e-09 0.026825 0.138390 0.985447
3 0.027268 0.012565 6.483388e-09 0.023292 0.125573 0.988299
  
Number of gaussian 4
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.016892 0.014278 2.484651e-09 0.014534 0.077833 0.995489
1 0.010297 0.014755 2.814803e-09 0.015271 0.082805 0.994956
2 0.019107 0.013089 2.237754e-09 0.013856 0.073895 0.995918
3 0.009939 0.015787 2.809077e-09 0.015380 0.082762 0.994927
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.029586 0.013883 3.957183e-09 0.018102 0.098224 0.992928
1 0.013863 0.019710 4.546694e-09 0.020180 0.105433 0.991544
2 0.028793 0.009819 4.377546e-09 0.018785 0.103184 0.992280
3 0.011108 0.016984 4.238517e-09 0.019007 0.101643 0.992301
  
Number of gaussian 5
Train
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.004241 0.007908 1.332088e-09 0.010656 0.056988 0.997597
1 0.008156 0.011457 1.490293e-09 0.011228 0.060238 0.997309
2 0.008437 0.013733 1.618343e-09 0.011760 0.062832 0.997052
3 0.012240 0.007341 1.441953e-09 0.010912 0.059320 0.997396
Test
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
0 0.006933 0.010074 3.373808e-09 0.016648 0.090706 0.993848
1 0.018364 0.015338 2.956191e-09 0.015761 0.085072 0.994628
2 0.010414 0.011580 3.775898e-09 0.017309 0.095873 0.993328
3 0.013799 0.012823 4.260830e-09 0.019638 0.101785 0.992265
Wall time: 1min 28s
In [76]:
train_scores_mean, train_scores_std = generate_mean_std_gof(CV_result_train_all)
print('Train gof mean, std')
display(train_scores_mean)

test_scores_mean, test_scores_std = generate_mean_std_gof(CV_result_test_all)
print('Test gof mean, std')
display(test_scores_mean)
Train gof mean, std
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
1 0.027660 0.040487 2.953421e-08 0.049943 0.268340 0.946559
2 0.022021 0.028832 1.063433e-08 0.029968 0.161013 0.980759
3 0.022196 0.013589 5.267172e-09 0.021091 0.113314 0.990469
4 0.014059 0.014477 2.586571e-09 0.014760 0.079324 0.995323
5 0.008268 0.010110 1.470669e-09 0.011139 0.059844 0.997338
Test gof mean, std
Chi_square K_S MSE RMSE / Max RMSE / Mean R_square
1 0.030319 0.040707 3.054035e-08 0.050714 0.272731 0.944786
2 0.024850 0.029206 1.198503e-08 0.031702 0.170878 0.978354
3 0.025292 0.013837 7.179293e-09 0.024635 0.132217 0.987023
4 0.020838 0.015099 4.279985e-09 0.019018 0.102121 0.992263
5 0.012377 0.012454 3.591682e-09 0.017339 0.093359 0.993517
In [77]:
prop_cycle=mpl.rcParams['axes.color_cycle']
gaussian_number_range = train_scores_mean.index
for column, column_name in zip(['R_square','K_S','Chi_square'],["$\ R^2$", "K-S", "$\widetilde{\chi^2} $"]):
    plot(gaussian_number_range, train_scores_mean[column],
             '--', label = 'training', color=prop_cycle[0])
    plt.fill_between(gaussian_number_range, 
                     train_scores_mean[column] - train_scores_std[column],
                     train_scores_mean[column] + train_scores_std[column], 
                     alpha=0.2, color=prop_cycle[0])
    
    plot(gaussian_number_range, test_scores_mean[column],
             '-', label = 'test',color=prop_cycle[1])
    plt.fill_between(gaussian_number_range, 
                 test_scores_mean[column] - test_scores_std[column],
                 test_scores_mean[column] + test_scores_std[column], 
                 alpha=0.2,color=prop_cycle[1])
    plt.xticks(gaussian_number_range)
    print(column)
    plt.locator_params(axis='y', nbins=5)
    plt_configure(xlabel='Number of Gaussian Distributions', ylabel=column_name, 
                  figsize=(3,2), legend={'loc':'best'})
    if column == 'R_square':
        plt.gca().set_ylim(top=1)
    if column == 'K_S' or column == 'Chi_square':
        plt.gca().set_ylim(bottom=0)
    plt.show()
R_square
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
  warnings.warn(self.msg_depr % (key, alt_key))
K_S
Chi_square
In [ ]:
for fig in [fig_hist, fig_kde, fig_em, fig_gmm]:
    display(fig)
for fig in [fig_time_variability_3d, fig_time_variability_cdf, fig_time_variability_weibull, 
            fig_adjecent_variability_3d, fig_adjecent_variability_cdf, fig_adjecent_variability_weibull,]:
    display(fig)
In [ ]:
import time
save_notebook()
time.sleep(3)
location_name = get_location_name(file_path)
print(location_name)
current_file = 'GMM.ipynb'
output_file = './output_HTML/'+location_name+'.html' 
output_HTML(current_file, output_file)